from django.shortcuts import render_to_response, redirect
from django.views.decorators.csrf import csrf_protect
from agbay.models import AgbayUsers, Items, Ratings, Notifications
from datetime import datetime
from django.core import validators
from django.contrib.auth.models import User
#from django.contrib.auth import authenticate, login

@csrf_protect
def register(request):
	return render_to_response('registration_form.html')
	
	
def profile_page(request, username):
	
	if request.method == 'GET':
		if request.session['current_user']==username:
			flag = True
		else:
			flag = False
	viewed_user = AgbayUsers.objects.get(Name = username)
	
	return render_to_response('user_profile.html', {'p_username': viewed_user.Name, 'p_email': viewed_user.Email, 'p_cdate': viewed_user.CreatedAt, 'p_udate': viewed_user.UpdatedAt, 'flag': flag})
 
 
def link(request,username):
	return render_to_response('get_profile_page.html', {'u': username})

def name_list(request, flag = None):
	list_of_users = AgbayUsers.objects.all()
	return render_to_response('get_profile_page.html', {'list_of_users': list_of_users, 'flag': flag})
	
def getParam(request):
		
	pass2R_error = ""
	usernameR_error = ""
	emailR_error = ""
	
	if request.method == 'POST':
		new_user = request.POST.get('nameParam')
		new_email = request.POST.get('emailParam')
		new_password = request.POST.get('pass1Param')
		new_password1 = request.POST.get('pass2Param')
		create_time = datetime.now()
		update_time = datetime.now()
	
	#check for empty string value
	if (new_user!="")&(new_email!="")&(new_password!="")&(new_password1 !=""):
		new_profile = AgbayUsers(Name = new_user,
								Email = new_email,
								Password = new_password,
								CreatedAt = create_time,
								UpdatedAt = update_time)
		#check for used username
		if not AgbayUsers.objects.filter(Name=new_user):
			#check for used email
			if not AgbayUsers.objects.filter(Email=new_email):
				#check for matching password
				if new_password == new_password1:
					#new_profilse.is_active() = False
					new_profile.save()
					#return render_to_response('user_profile.html', { 'p_username': new_user, 'p_email': new_email, 'p_cdate': create_time, 'p_udate': update_time})
					return attempt_login(request, nameParam = new_profile.Name, passwordParam = new_profile.Password)
				else:
					pass2R_error = "Password is not matched."
			else: 
				emailR_error = (' "%s" is already in use. Please supply a different email address.' % new_email)
		else:
			usernameR_error = ('The username "%s" is already taken.' % new_user)
		return render_to_response('registration_form.html', { 'username_error': usernameR_error, 'password_error': pass2R_error, 'email_error': emailR_error })
		
	else:
		return render_to_response('registration_form.html', {'form_error': "One or more fields are not entered."})	
	
def update(request, username):

	if request.method == 'GET':
		updated_user = AgbayUsers.objects.get(Name = username)
	return render_to_response('update_profile.html', {'e_username': updated_user.Name, 'e_email': updated_user.Email, 'e_password': updated_user.Password})

def getUpdate(request, username):
	
	if request.method == 'POST':
		new_info = AgbayUsers.objects.get(Name = username)
		old_pass = new_info.Password
		old_email = new_info.Email
		
		entered_username = request.POST.get('nameParam')
		entered_email = request.POST.get('emailParam')
		entered_pass = request.POST.get('pass1Param')
		new_pass2 = request.POST.get('pass2Param')
		new_pass3 = request.POST.get('pass3Param')
		new_info.UpdatedAt = datetime.now()
		
		
	#check for empty string value
	if (entered_pass==""):
		pass1U_error = "Please enter your current password."
		return render_to_response('update_profile.html', {'password1_errors' : pass1U_error, 'e_username': username, 'e_email': old_email})
		
	if(entered_username ==""):
		usernameU_error = "Please enter your username."
		return render_to_response('update_profile.html', {'username_errors' : usernameU_error, 'e_username': username, 'e_email': old_email})
	else:
		if username != entered_username:	
			if not AgbayUsers.objects.filter(Name__iexact = entered_username):
				new_info.Name = entered_username
			else:
				usernameU_error = "Username already in use.  Please enter a different username."
				return render_to_response('update_profile.html', {'username_errors' : usernameU_error, 'e_username': username, 'e_email': old_email})
	
	if (entered_pass!=""):
		if (entered_pass == old_pass): #check for correct current password
			if (new_pass2 == "") & (new_pass3==""): #use current password (i.e. no password change)
				if (entered_email == old_email): #use current email
					return render_to_response('user_profile.html', { 'p_username': new_info.Name, 'p_email': new_info.Email, 'p_cdate': new_info.CreatedAt, 'p_udate': new_info.UpdatedAt})
				else: #change email address
					if not AgbayUsers.objects.filter(Email__iexact = entered_email): #check for used email address
						new_info.Email = entered_email
					else:
						emailU_error = "This email address is already in use. Please supply a different email address."
						return render_to_response('update_profile.html', {'email_errors' : email_errors, 'e_username': username, 'e_email': old_email})

			else: #change password
				if (new_pass2 == new_pass3):
					new_info.Password = new_pass2
				else:
					pass3U_error = "Confirmed password is not matched."
					return render_to_response('update_profile.html', {'password3_errors' : pass3U_error, 'e_username': username, 'e_email': old_email})
		else:
			pass2U_error = "Your current password does not match with what we have in our record.  Please try again."
			return render_to_response('update_profile.html', { 'password1_errors' : pass2U_error, 'e_username': username, 'e_email': old_email})
					
	new_info.save()
	return render_to_response('user_profile.html', { 'p_username': new_info.Name, 'p_email': new_info.Email, 'p_cdate': new_info.CreatedAt, 'p_udate': new_info.UpdatedAt})
	
def delete_user(request, username):
	user = AgbayUsers.objects.get(Name=username)
	#dummy_user = AgbayUsers.objects.get(Name='Deleted User')
	#for item in Items.objects.raw('SELECT * FROM agbay_items WHERE SellerUserId = %s Or BuyerUserId = %s', [user_id, user_id]) :
	for item in Items.objects.filter(SellerUserId = user.id).filter(BuyerUserId = user.id) :
		# Delete all related notifications
		#Bids.objects.filter(UserId = user.id).delete() 
		if item.IsCompleted :
			if item.SellerUserId == user.id & item.BuyerUserId != dummy_user.id :
				item.BuyerUserId = dummy_user.pk
				item.save()
			elif item.BuyerUserId == user.id & item.SellerUserId != dummy_user.id :
				item.SellerUserId = dummy_user.id
				item.save()
			else :
				item.delete()
		else :
			if item.BuyerUserId == user.id :
				continue # same as decline purchase
			else :
				# Notify the buyer of deletion (maybe wait to delete until buyer acknowledges that way a notification can be generated correctly with the item)
				item.delete()
	for rating in Ratings.objects.filter(RateeUserId = user.id).filter(RaterUserId = user.id):
		# delete all related notifications
		if rating.RateeUserId == user.id :
			rating.delete()
		else :
			rating.Rater = dummy_user.id
			rating.save()
	user.delete()
	msg = "Profile Deleted"
	return render_to_response('delete_user.html', {"error_msg": msg})	

def login(request):
	return render_to_response('login.html')
	

def attempt_login(request, nameParam = None, passwordParam = None):
	if (nameParam is not None) & (passwordParam is not None):
		name = nameParam
		pw = passwordParam
	else:
		name = request.POST['nameParam']
		pw = request.POST['passwordParam']
		
	u = AgbayUsers.objects.filter(Name = name, Password = pw)
	list_of_users = AgbayUsers.objects.all()
	if (u.count() == 0):
		return render_to_response('login.html', {"error_msg": "Incorrect username or password",'username': name, 'password': pw})
	else:
		request.session['current_user'] = name
		msg = "Correct! Welcome, ", request.session['current_user']
		return render_to_response('get_profile_page.html', {"error_msg": msg, 'list_of_users': list_of_users})

def create_item(request):
	try:
		if request.session['current_user'] == None:
			return render_to_response('create_item.html', {'form_error': "Must be logged in to create item."})
		return render_to_response('create_item.html', {'form_error' : None})
	except:
		return render_to_response('create_item.html', {'form_error': "Must be logged in to create item."})
	
def getItem(request):
	viewed_user = AgbayUsers.objects.get(Name = request.session['current_user'])
	if request.method == 'POST':
		mid_bid = request.POST.get('midBidParam')
		max_bid = request.POST.get('maxBidParam')
		create_time = datetime.now()
		update_time = datetime.now()
		
	#check for empty string value
	if (mid_bid!="")&(max_bid!=""):
		new_item = Items(SellerUserId = viewed_user,	
						 BuyerUserId = viewed_user,		# need to fix
						 MinBid = mid_bid,
						 MaxBid = max_bid,
						 CurBid = 0,
						 BuyPrice = 0,					# wasn't sure what value to assign
						 IsCompleted = 0,				# wasn't sure what value to assign
						 CreatedAt = create_time,
						 UpdatedAt = update_time,
						 EndingAt = create_time)		# need to fix
		#new_item.is_active() = False
		new_item.save()
		return items_list(request)
		
	else:
		return render_to_response('create_item.html', {'form_error' : None, 'item_error': "One or more fields are not entered."})	

def items_list(request):
	list_of_items = Items.objects.all()
	return render_to_response('items.html', {'list_of_items': list_of_items})

def item_page(request, item_id):
	item = Items.objects.get(id = item_id)
	return render_to_response('items_page.html', {'item' : item})
	
def view_notifications(request, username):
	user = AgbayUsers.objects.get(Name = username)
	list_of_notifications = Notifications.objects.all()
	for notification in list_of_notifications:
		# Decide which types are ratings or items
		if notification.Type == 1: # item
			item = Items.objects.get(id = notification.RelatedRatingOrItemId)
			if item.SellerUserId != user.id and item.BuyerUserId != user.id:
				list_of_notifications.erase(notification)
		elif notification.Type == 2: # rating
			rating = Ratings.objects.get(id = notification.RelatedRatingOrItemId)
			if rating.RateeUserId != user.id and rating.RaterUserId != user.id:
				list_of_notifications.erase(notification)
	return render_to_response('profile_notifications.html', {'list_of_notifications': list_of_notifications})
	
def bid(request):
	return render_to_response('bid.html')

def rating(request):
	return render_to_response('rating.html')

def get_rating(request, username):
		if request.session['current_user']==username:
			rate_error = "You can't rate yourself!"
			return render_to_response('rating.html', {'rate_error': rate_error})	
		else:
			rate_value = request.POST.get('rateParam')
			ratee = AgBayUser.objects.get(Name = username).Id
			rater = AgBayUser.objects.get(Name = request.session['current_user']).Id
			reason = request.POST.get('comments')
			create_time = datetime.now()
			update_time = datetime.now()
			
			new_rating = Ratings(RateeUserId = ratee,
								 RaterUserId = rater,
								 Rating = rate_value,
								 Reason = reason,
								 IsReport = False,
								 CreatedAt = datetime.now(),
								 UpdatedAt = datetime.now())
			new_rating.save()